package com.waves.message.events;

import cn.hutool.core.lang.Assert;
import com.waves.message.checker.GoodTimeChecker;
import com.waves.message.entity.MessageRecord;
import com.waves.message.enums.NoticeTypeEnums;
import com.waves.message.strategy.INoticeStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.matcher.ElementMatchers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author Eden
 * @date 2025/01/01 16:12
 **/
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SendMessageEventProcessor {


    @EventListener
    public void handlerInsert(
            ISendMessageEvent.insertEvent insertEvent) throws InstantiationException, IllegalAccessException {
        MessageRecord messageRecord = insertEvent.getMessageRecord();
        log.info("Insert message record: {}", messageRecord);
        //校验
        boolean matches = ElementMatchers.any()
                                         .and(new GoodTimeChecker()) //1分钟内是否有消息推送过
                                         .matches(messageRecord);
        Assert.isTrue(matches, "1分钟之内不能重复推送消息");
        //三方消息发送,消息中间件
        //枚举工厂+策略实现消息方法
        Optional<NoticeTypeEnums> enumByCode = NoticeTypeEnums.getEnumByCode(
                messageRecord.getNoticeType());
        boolean present = enumByCode.isPresent();
        if (present) {
            Class<? extends INoticeStrategy> noticeStrategy = enumByCode.get()
                                                                        .getNoticeStrategy();
            if (noticeStrategy != null) {
                noticeStrategy.newInstance()
                              .sendMessage(messageRecord);
            }

        }

    }


}

